package com.cxf.windex.base.rest;

import com.alibaba.fastjson.JSONObject;
import com.cxf.windex.base.secruity.JwtUser;
import com.cxf.windex.base.util.MapCache;
import com.cxf.windex.componets.SiteCommon;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author chenxf
 * @date 4/11/2018
 * @description
 */
public class BaseController {

  @Autowired
  private SiteCommon siteCommon;

  public static String THEME = "themes/default";

  protected MapCache cache = MapCache.single();

  protected Map<String, Object> resultMap = new HashMap<String, Object>();

  public String render(String viewName) {
    return THEME + "/" + viewName;
  }

  public void initSeo(Map map,String title,String keywords,String description){
    this.title(map,title);
    this.keywords(map,keywords);
    this.description(map,description);
  }

  public void title(Map map, String title) {
    if(StringUtils.isNotBlank(title)){
      title=title+"-"+siteCommon.getName();
    }else{
      title=siteCommon.getName();
    }
   map.put("title", title);

  }

  public void keywords(Map map, String keywords) {
    if(StringUtils.isNotBlank(keywords)){
      keywords=keywords+"-"+siteCommon.getKeywords();
    }else{
      keywords=siteCommon.getKeywords();
    }
    map.put("keywords", keywords);

  }

  public void description(Map map, String description) {
    if(StringUtils.isNotBlank(description)){
      description=description+"-"+siteCommon.getDescrption();
    }else{
      description=siteCommon.getDescrption();
    }
    map.put("description", description);

  }

  public String json(int code, String message) {
    resultMap.put("code", code);
    resultMap.put("msg", message);
    return new JSONObject(resultMap).toString();
  }

  public String render_404() {
    return "/comm/error_404";
  }
  public String getCurrentUserId(){
      SecurityContext sc = SecurityContextHolder.getContext();
      if(sc.getAuthentication()==null){
        return "";
      }
      Object principal = sc.getAuthentication().getDetails();
      if (principal instanceof JwtUser) {
        JwtUser user = (JwtUser) principal;
        return user.getId();
      }
   return "";
  }



}
